package com.yanqu.road.server.gameplayer.module.activity.qixi;

import com.yanqu.road.dao.impl.player.UserQixiDaoImpl;
import com.yanqu.road.dao.impl.player.UserQixiGiftDaoImpl;
import com.yanqu.road.dao.impl.player.UserQixiRelationDaoImpl;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogQixiReceiveBroadcast;
import com.yanqu.road.entity.log.LogQixiReceiveFlower;
import com.yanqu.road.entity.log.LogQixiSendFlower;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.qixi.UserQixiData;
import com.yanqu.road.entity.qixi.UserQixiGiftData;
import com.yanqu.road.entity.qixi.UserQixiRelationData;
import com.yanqu.road.entity.relatives.RelativesInfo;
import com.yanqu.road.entity.servercenter.GameEditLimit;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.QixiProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.gameplayer.module.relatives.RelativesModule;
import com.yanqu.road.server.manger.ForbiddenMgr;
import com.yanqu.road.server.manger.ForbiddenWordMgr;
import com.yanqu.road.server.manger.GameEditLimitMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.logic.activity.qixi.QixiConfig;
import com.yanqu.road.server.manger.activity.qixi.QixiMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.relatives.RelativesMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.*;
import com.yanqu.road.sync.message.SyncResponse;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.mina.util.ConcurrentHashSet;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

public class QixiModule extends GeneralModule {
    public QixiModule(GamePlayer player) {
        super(player);
    }

    private UserQixiData userData;
    private List<UserQixiGiftData> userGiftList = new ArrayList<>();
    private List<UserQixiGiftData> needUpdateGiftList = new ArrayList<>();
    private Map<Long, UserQixiRelationData> userRelationMap = new ConcurrentHashMap<>();

    /**
     * 送出去等待返回处理的玩家
     */
    private Set<Long> waitSendFlowerBackUserIdSet = new ConcurrentHashSet<>();

    @Override
    public boolean loadData() {
        if (QixiMgr.getConfig() == null) {
            return true;
        }
        UserQixiData tempUserData = new UserQixiDaoImpl().getUserQixiData(QixiMgr.getConfig().getActivityId(), player.getUserId());
        Map<Long, UserQixiRelationData> tempRelationDataMap = new UserQixiRelationDaoImpl().getUserQixiRelationDataMap(QixiMgr.getConfig().getActivityId(), player.getUserId());
        List<UserQixiGiftData> tempGiftList = new UserQixiGiftDaoImpl().getUserQixiGiftDataList(QixiMgr.getConfig().getActivityId(), player.getUserId());

        userData = tempUserData;
        userRelationMap = tempRelationDataMap;
        userGiftList = tempGiftList;

        initUserData();
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                new UserQixiDaoImpl().add(userData);
            } else if (userData.isUpdateOption()) {
                new UserQixiDaoImpl().update(userData);
            }
        }

        List<UserQixiRelationData> relationDataList;
        synchronized (userRelationMap) {
            relationDataList = new ArrayList<>(userRelationMap.values());
        }

        for (UserQixiRelationData userQixiRelationData : relationDataList) {
            if (userQixiRelationData.isInsertOption()) {
                new UserQixiRelationDaoImpl().add(userQixiRelationData);
            } else if (userQixiRelationData.isUpdateOption()) {
                new UserQixiRelationDaoImpl().update(userQixiRelationData);
            }
        }

        synchronized (userGiftList) {
            for (UserQixiGiftData userQixiGiftData : userGiftList) {
                if (userQixiGiftData.isInsertOption()) {
                    new UserQixiGiftDaoImpl().add(userQixiGiftData);
                } else if (userQixiGiftData.isUpdateOption()) {
                    new UserQixiGiftDaoImpl().update(userQixiGiftData);
                }
            }

            for (UserQixiGiftData userQixiGiftData : needUpdateGiftList) {
                if (userQixiGiftData.isInsertOption()) {
                    new UserQixiGiftDaoImpl().add(userQixiGiftData);
                } else if (userQixiGiftData.isUpdateOption()) {
                    new UserQixiGiftDaoImpl().update(userQixiGiftData);
                }
            }
            needUpdateGiftList.clear();
        }


        return true;
    }

    @Override
    public void afterLogin() {
        initUserData();
        resetOneDay(true);
        removeOverBroadcastId();
        syncUserData();
        loginReqBroadcast();
        syncAllOpenServerList();

        int ret = checkActivityRet();
        if (ret == 0 && !userRelationMap.isEmpty()) {
            int totalValue = 0;
            int totalSend = 0;
            synchronized (userRelationMap) {
                for (UserQixiRelationData relationData : userRelationMap.values()) {
                    totalValue += relationData.getGetFlowerCount();
                    totalSend += relationData.getSendFlowerCount();
                }
            }
            if (totalValue != userData.getGetFlowerCount()) {
                userData.setGetFlowerCount(totalValue);
                player.notifyListener(eGamePlayerEventType.QixiUserRank.getValue(), userData.getGetFlowerCount());
            }
            if (totalSend != userData.getSendFlowerCount()){
                userData.setSendFlowerCount(totalSend);
            }
        }
    }

    public void initSystem() {
        initUserData();
        syncUserData();
    }

    public boolean isSystemOpen() {
        return SystemOpenMgr.systemOpen(player, eSystemId.Qixi.getValue());
    }

    public int checkActivityRet() {
        if (userData == null) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if (QixiMgr.getConfig() == null || QixiMgr.getConfig().getActivityId() != userData.getActivityId()) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (!ActivityMgr.activityInTime(QixiMgr.getConfig().getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        return 0;
    }

    public int checkActivityShowRet() {
        if (userData == null) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if (QixiMgr.getConfig() == null || QixiMgr.getConfig().getActivityId() != userData.getActivityId()) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (!ActivityMgr.activityInShowTime(QixiMgr.getConfig().getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        return 0;
    }

    public synchronized void initUserData() {
        if (!isSystemOpen()) {
            return;
        }

        QixiConfig config = QixiMgr.getConfig();
        if (config == null) {
            return;
        }
        if (null == userData || userData.getActivityId() != config.getActivityId()) {
            userData = new UserQixiData(config.getActivityId(), player.getUserId());
            userRelationMap.clear();
        }
    }

    public void syncUserData() {
        if (userData == null) {
            return;
        }
        if (player.getState() != PlayerState.ONLINE) {//玩家在线才执行
            return;
        }
        QixiProto.QixiUserSyncMsg.Builder syncMsg = QixiProto.QixiUserSyncMsg.newBuilder();
        syncMsg.setActivityId(userData.getActivityId());
        syncMsg.setGetFlowerCount(userData.getGetFlowerCount());
        syncMsg.setSendFlowerCount(userData.getSendFlowerCount());
        syncMsg.setDayCount1(userData.getDayCount1());
        syncMsg.setDayCount2(userData.getDayCount2());
        syncMsg.setDayCount3(userData.getDayCount3());
        syncMsg.setHaveGift(!userGiftList.isEmpty());

        player.sendPacket(ClientProtocol.U_QIXI_USER_SYNC, syncMsg);
    }

    public void syncAllOpenServerList() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return;
        }
        QixiProto.QixiAllOpenServerListSyncMsg.Builder allOpenServerListMsg = QixiMgr.getAllOpenServerListMsg();
        player.sendPacket(ClientProtocol.U_QIXI_ALL_OPEN_SERVER_LIST, allOpenServerListMsg);
    }

    public void loginReqBroadcast() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return;
        }
        QixiProto.CrossLoginGetFlowerBroadcastReqMsg.Builder crossMsg = QixiProto.CrossLoginGetFlowerBroadcastReqMsg.newBuilder();
        crossMsg.setActivityId(QixiMgr.getConfig().getActivityId());
        crossMsg.addAllExcludeId(userData.getWatchBroadcastList());
        player.sendPacket(CrossProtocol.C_QIXI_LOGIN_GET_FLOWER_BROADCAST, crossMsg);
    }

    public void resetOneDay(boolean isLogin) {
        if (userData == null) {
            return;
        }
        long currentTime = DateHelper.getCurrentTime();
        if (!DateHelper.isSameDay(currentTime / 1000, userData.getLastGetTime() / 1000)) {
            userData.setDayCount1(0);
            userData.setDayCount2(0);
            userData.setDayCount3(0);
            userData.setLastGetTime(currentTime);
            if (!isLogin) {
                syncUserData();
            }
        }
    }

    public UserQixiRelationData getTargetRelation(long targetUserId) {
        return userRelationMap.get(targetUserId);
    }

    public void addTargetRelation(UserQixiRelationData relationData) {
        synchronized (userRelationMap) {
            userRelationMap.put(relationData.getTargetUserId(), relationData);
        }
    }

    /**
     * 2	商会页签展示排序
     * 1	优先展示商会中有互动的玩家
     * 1	玩家赠送过花的对象
     * 2	玩家收到过花的对象
     * 2	都有互动时，优先展示赠花/收花数量大的人员
     * 2	赠花/收花数量相同时，赠花的在前面
     * 3	赠花也相同时，对方赚速高的在前面
     * <p>
     * 3	世交页签展示排序
     * 1	优先展示世交中有互动的玩家
     * 1	玩家赠送过花的对象
     * 2	玩家收到过花的对象
     * 2	都有互动时，优先展示赠花/收花数量大的人员
     * 2	赠花/收花数量相同时，赠花的在前面
     * 3	赠花也相同时，对方赚速高的在前面
     * <p>
     * 4	往来页签展示排序
     * 1	往来页签中，只显示有互动的玩家
     * 1	玩家赠送过花的对象
     * 2	玩家收到过花的对象
     * 2	往来人员排序规则
     * 1	优先展示赠花/收花数量大的人员
     * 2	赠花/收花数量相同时，赠花的在前面
     * 3	赠花也相同时，对方赚速高的在前面
     * 3	往来页签中，最多显示20人。
     *
     * @param tapType
     * @return
     */
    public int getRelationList(int tapType) {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        Map<Long, Set<Long>> needUserInfoFromOtherServer = new HashMap<>();

        QixiProto.QixiRelationListRespMsg.Builder respMsg = QixiProto.QixiRelationListRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(QixiMgr.getConfig().getActivityId());
        respMsg.setTapType(tapType);
        if (tapType == 1) {//商会成员
            String unionUid = player.getUserInfo().getUnionUid();
            CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            if (unionInfo != null) {
                Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
                for (CrossUnionMember unionMember : unionMemberMap.values()) {
                    if (unionMember.getUserId() == player.getUserId()) {
                        continue;
                    }
                    QixiProto.QixiRelationTemp.Builder relationTemp = QixiProto.QixiRelationTemp.newBuilder();
                    relationTemp.setTargetUserId(unionMember.getUserId());
                    relationTemp.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(unionMember.getUserBaseInfo()));
                    UserQixiRelationData targetRelation = getTargetRelation(unionMember.getUserId());
                    if (targetRelation != null) {
                        relationTemp.setGetFlowerCount(targetRelation.getGetFlowerCount());
                        relationTemp.setSendFlowerCount(targetRelation.getSendFlowerCount());
                    } else {
                        relationTemp.setGetFlowerCount(0);
                        relationTemp.setSendFlowerCount(0);
                    }
                    respMsg.addRelationList(relationTemp);
                }
            }
        } else if (tapType == 2) {//世家
            Map<Long, RelativesInfo> relativesMap = player.getModule(RelativesModule.class).getRelativesMap();
            for (RelativesInfo relativesInfo : relativesMap.values()) {
                if (relativesInfo.getStatus() != 1) {
                    continue;
                }
                long targetUserId = 0;
                if (relativesInfo.getUserId1() == player.getUserId()) {
                    targetUserId = relativesInfo.getUserId2();
                } else {
                    targetUserId = relativesInfo.getUserId1();
                }
                QixiProto.QixiRelationTemp.Builder relationTemp = QixiProto.QixiRelationTemp.newBuilder();
                relationTemp.setTargetUserId(targetUserId);
                relationTemp.setGetFlowerCount(0);
                relationTemp.setSendFlowerCount(0);
                UserQixiRelationData targetRelation = getTargetRelation(targetUserId);
                if (targetRelation != null) {
                    relationTemp.setGetFlowerCount(targetRelation.getGetFlowerCount());
                    relationTemp.setSendFlowerCount(targetRelation.getSendFlowerCount());
                }

                PlayerProto.PlayerBaseTempMsg playerBaseTempMsg = QixiMgr.getCacheUserInfo(targetUserId);
                if (playerBaseTempMsg != null) {
                    relationTemp.setUserBaseInfo(playerBaseTempMsg);
                } else {
                    UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(targetUserId, GameServer.getInstance().getServerId());
                    if (userBaseInfo == null) {
                        //本服没有去商会找一下
                        CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(targetUserId);
                        if (unionMember == null) {
                            //商会也没有跨服拉一下
                            long targetServerId = RelativesMgr.getUserServerId(targetUserId);
                            Set<Long> userIds = needUserInfoFromOtherServer.get(targetServerId);
                            if (userIds == null) {
                                userIds = new HashSet<>();
                                needUserInfoFromOtherServer.put(targetServerId, userIds);
                            }
                            userIds.add(targetUserId);

                            continue;
                        } else {
                            userBaseInfo = unionMember.getUserBaseInfo();
                        }
                    }

                    relationTemp.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                }


                respMsg.addRelationList(relationTemp);
            }

        } else if (tapType == 3) {//往来关系前20
            List<UserQixiRelationData> relationDataList = new ArrayList<>(userRelationMap.values());
            relationDataList.sort((o1, o2) -> {
                int compare = Integer.compare(o2.getGetFlowerCount() + o2.getSendFlowerCount(), o1.getGetFlowerCount() + o1.getSendFlowerCount());
                if (compare == 0) {
                    compare = Integer.compare(o2.getSendFlowerCount(), o1.getSendFlowerCount());
                }
                if (compare == 0) {
                    compare = Integer.compare(o2.getGetFlowerCount(), o1.getGetFlowerCount());
                }
                if (compare == 0) {
                    compare = Long.compare(o1.getSendTime(), o2.getSendTime());
                }

                return compare;
            });

            for (int i = 0; i < relationDataList.size() && i < QixiMgr.getConfig().getQIXI_GIVE_AWAY_RECORD(); i++) {
                UserQixiRelationData qixiRelationData = relationDataList.get(i);
                long targetUserId = qixiRelationData.getTargetUserId();
                QixiProto.QixiRelationTemp.Builder relationTemp = QixiProto.QixiRelationTemp.newBuilder();
                relationTemp.setTargetUserId(qixiRelationData.getTargetUserId());
                relationTemp.setGetFlowerCount(qixiRelationData.getGetFlowerCount());
                relationTemp.setSendFlowerCount(qixiRelationData.getSendFlowerCount());

                PlayerProto.PlayerBaseTempMsg playerBaseTempMsg = QixiMgr.getCacheUserInfo(targetUserId);
                if (playerBaseTempMsg != null) {
                    relationTemp.setUserBaseInfo(playerBaseTempMsg);
                } else {
                    UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(targetUserId, GameServer.getInstance().getServerId());
                    if (userBaseInfo == null) {
                        //本服没有去商会找一下
                        CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(targetUserId);
                        if (unionMember == null) {
                            //商会也没有跨服拉一下
                            long targetServerId = RelativesMgr.getUserServerId(targetUserId);
                            Set<Long> userIds = needUserInfoFromOtherServer.get(targetServerId);
                            if (userIds == null) {
                                userIds = new HashSet<>();
                                needUserInfoFromOtherServer.put(targetServerId, userIds);
                            }
                            userIds.add(targetUserId);

                            continue;
                        } else {
                            userBaseInfo = unionMember.getUserBaseInfo();
                        }
                    }
                    relationTemp.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                }

                respMsg.addRelationList(relationTemp);
            }
        }

        player.sendPacket(ClientProtocol.U_QIXI_GET_RELATION_LIST, respMsg);

        if (!needUserInfoFromOtherServer.isEmpty()) {
            for (Map.Entry<Long, Set<Long>> entry : needUserInfoFromOtherServer.entrySet()) {
                Long serverId = entry.getKey();
                Set<Long> userIds = entry.getValue();

                QixiProto.QixiGetUserInfoReqMsg.Builder reqMsg = QixiProto.QixiGetUserInfoReqMsg.newBuilder();
                reqMsg.setActivityId(QixiMgr.getConfig().getActivityId());
                reqMsg.addAllTargetUserId(userIds);
                reqMsg.setReqProtocolType(GameProtocol.S_QIXI_GET_RELATION_LIST);

                QixiProto.QixiGetUserInfoRespMsg.Builder resp = QixiProto.QixiGetUserInfoRespMsg.newBuilder();

                CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(serverId, GameProtocol.S_QIXI_GET_USER_INFO, player.getUserId(), reqMsg, resp);
                future.thenAccept((SyncResponse syncResponse) -> {
                    QixiProto.QixiRelationListRespMsg.Builder builder = QixiProto.QixiRelationListRespMsg.newBuilder();
                    builder.setRet(0);

                    if (syncResponse.getErrorCode() != 0) {
                        builder.setRet(syncResponse.getErrorCode());
                    }
                    if (resp.getReqProtocolType() != GameProtocol.S_QIXI_GET_RELATION_LIST) {
                        return;
                    }

                    builder.setTapType(tapType);
                    builder.setActivityId(QixiMgr.getConfig().getActivityId());

                    for (QixiProto.QixiRelationTemp temp : resp.getRelationListList()) {
                        QixiProto.QixiRelationTemp.Builder relationTemp = QixiProto.QixiRelationTemp.newBuilder();
                        relationTemp.setUserBaseInfo(temp.getUserBaseInfo());
                        relationTemp.setTargetUserId(temp.getTargetUserId());
                        relationTemp.setGetFlowerCount(0);
                        relationTemp.setSendFlowerCount(0);
                        UserQixiRelationData targetRelation = getTargetRelation(temp.getTargetUserId());
                        if (targetRelation != null) {
                            relationTemp.setGetFlowerCount(targetRelation.getGetFlowerCount());
                            relationTemp.setSendFlowerCount(targetRelation.getSendFlowerCount());
                        }
                        builder.addRelationList(relationTemp);

                        QixiMgr.addCacheUserInfo(temp.getTargetUserId(), temp.getUserBaseInfo());
                    }

                    player.sendPacket(ClientProtocol.U_QIXI_GET_RELATION_LIST, builder);
                });
            }
        }


        return 0;
    }

    public int getRelationList(long watchUserId, long watchUserServerId) {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        long serverId = ConfigHelper.getLong("serverId");

        if(serverId != watchUserServerId){
            // 到玩家区服
            QixiProto.QixiRelationTopGetListReqMsg.Builder reqMsg = QixiProto.QixiRelationTopGetListReqMsg.newBuilder();
            reqMsg.setActivityId(QixiMgr.getConfig().getActivityId());
            reqMsg.setServerId(watchUserServerId);
            reqMsg.setTargetUserId(watchUserId);

            QixiProto.QixiRelationTopGetListRespMsg.Builder clientMsg = QixiProto.QixiRelationTopGetListRespMsg.newBuilder();
            CompletableFuture<SyncResponse> responseFuture = GamePlayerMgr.sendToGameServer(watchUserServerId, GameProtocol.S_QIXI_GET_RELATION_TOP_GET_LIST_SERVICE, player.getUserId(), reqMsg, clientMsg);
            responseFuture.thenAccept(syncResponse -> {
                if(syncResponse.getErrorCode() == 0){
                    player.sendPacket(Protocol.U_QIXI_GET_RELATION_TOP_GET_LIST, clientMsg);
                }
            });
            return 0;
        }

        QixiProto.QixiRelationTopGetListRespMsg.Builder respMsg = QixiProto.QixiRelationTopGetListRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(QixiMgr.getConfig().getActivityId());
        respMsg.setServerId(watchUserServerId);
        respMsg.setTargetUserId(watchUserId);
        Map<Long, UserQixiRelationData> relationDataMap;
        if(watchUserId == player.getUserId()) {
            relationDataMap = userRelationMap;
        }else {
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(watchUserId);
            if(onlinePlayer != null){
                relationDataMap = onlinePlayer.getModule(QixiModule.class).getUserRelationMap();
            }else {
                relationDataMap = new UserQixiRelationDaoImpl().getUserQixiRelationDataMap(QixiMgr.getConfig().getActivityId(), watchUserId);
            }
        }
        QixiMgr.buildRelation(serverId, respMsg, relationDataMap);

        player.sendPacket(ClientProtocol.U_QIXI_GET_RELATION_TOP_GET_LIST, respMsg);

        return 0;
    }

    /**
     * 送花
     *
     * @param reqMsg
     * @return
     */
    public int sendFlower(QixiProto.QixiSendFlowerReqMsg reqMsg) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        if (reqMsg.getTargetUserId() == player.getUserId()) {
            return GameErrorCode.E_QIXI_CAN_NOT_SEND_SELF;
        }

        //物品类别161 花满七夕道具  参数列表：送花数|戒指id|戒指数量|每日赠送上限|是否广播,   赠送上限-1表示无限制，0表示不广播，1广播
        GoodsInfo flowerInfo = GoodsMgr.getGoodsById(reqMsg.getFlowerId());
        if (flowerInfo == null) {
            return GameErrorCode.E_QIXI_FLOWER_USE_CONFIG_NOT_FOUND;
        }

        String content = reqMsg.getContent();
        if (flowerInfo.getParamList().get(4).intValue() == 1) {//需要广播的才判断宣言
            //编辑限制
            GameEditLimit gameEditLimit = GameEditLimitMgr.getGameEditLimit(Protocol.S_QIXI_SEND_FLOWER);
            if (null != gameEditLimit) {
                long nowTime = System.currentTimeMillis();
                if (nowTime >= gameEditLimit.getLimitEditStartTime() && nowTime < gameEditLimit.getLimitEditEndTime()) {
                    String replaceStr = ServerLanguageMgr.getContent(QixiMgr.getConfig().getQIXI_BROADCASTING_CONTENT(), player.getLanguage());
                    if (!StringUtils.isNullOrEmpty(gameEditLimit.getReplaceContent())) {
                        replaceStr = gameEditLimit.getReplaceContent();
                    }
                    content = replaceStr;
                }
            }
            /**
             * 送财功能被禁用 则返回系统未开放
             */
            if (ForbiddenMgr.isForbiddenCmd(player.getUserId(), Protocol.S_QIXI_SEND_FLOWER)) {
                return GameErrorCode.E_SYSTEM_NO_OPEN;
            }

            //留言屏蔽字判断
            if (ForbiddenWordMgr.isForbidden(content)) {
                return GameErrorCode.E_FORBIDDEN_WORD;
            }
            if (StringUtils.isNullOrEmpty(content)) {
                return GameErrorCode.E_FORBIDDEN_WORD;
            }
        } else {//不要广播的给个空字符串
            content = "";
        }


        int flowerUseNum = reqMsg.getFlowerCount();
        Property cost = new Property(flowerInfo.getGoodsId(), flowerUseNum);

        if (flowerUseNum == 0 || !player.getModule(CurrencyModule.class).currencyIsEnough(cost)) {
            return Integer.valueOf(GameErrorCode.E_BAG_ITEM_NO_ENOUGH);
        }

        if (flowerUseNum > flowerInfo.getCanUse()) {
            return GameErrorCode.E_QIXI_ONLY_SEND_ONE_FLOWER;
        }

        long targetServerId = RelativesMgr.getUserServerId(reqMsg.getTargetUserId());

        CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(reqMsg.getTargetUserId());
        if (unionMember != null) {
            targetServerId = unionMember.getServerId();
        } else {
            UserInfo userInfo = UserMgr.getUserInfo(reqMsg.getTargetUserId());
            if (userInfo != null) {
                targetServerId = userInfo.getOriginalServerId();
            }
        }

        if (waitSendFlowerBackUserIdSet.contains(reqMsg.getTargetUserId())) {
            QixiProto.QixiSendFlowerRespMsg.Builder waiMsg = QixiProto.QixiSendFlowerRespMsg.newBuilder();
            waiMsg.setRet(GameErrorCode.E_QIXI_WAIT_SEND_FLOWER_BACK);
            player.sendPacket(ClientProtocol.U_QIXI_WAIT_SEND_FLOWER_BACK, waiMsg);
            return -1;//返回-1等异步处理。
        }

        waitSendFlowerBackUserIdSet.add(reqMsg.getTargetUserId());

        if (targetServerId == GameServer.getInstance().getServerId()) {//本服送花
            QixiProto.CrossQixiSendFlowerRespMsg.Builder backMsg = QixiMgr.receiveFlower(GameServer.getInstance().getServerId(), player.getUserId(), reqMsg.getTargetUserId(), reqMsg.getFlowerId(), flowerUseNum, content);
            if (backMsg == null) {
                QixiProto.QixiSendFlowerRespMsg.Builder waiMsg = QixiProto.QixiSendFlowerRespMsg.newBuilder();
                waiMsg.setRet(GameErrorCode.E_QIXI_WAIT_SEND_FLOWER_BACK);
                player.sendPacket(ClientProtocol.U_QIXI_WAIT_SEND_FLOWER_BACK, waiMsg);
                return -1;//返回-1等异步处理。
            }

            player.getModule(PreReduceModule.class).preReduce(cost);//统一预扣

            sendFlowerSuccessBack(backMsg.build());

            return 0;
        } else {//跨服送花
            QixiProto.QixiSendFlowerReqMsg.Builder builder = QixiProto.QixiSendFlowerReqMsg.newBuilder();
            builder.setActivityId(QixiMgr.getConfig().getActivityId());
            builder.setTargetUserId(reqMsg.getTargetUserId());
            builder.setFlowerCount(reqMsg.getFlowerCount());
            builder.setFlowerId(reqMsg.getFlowerId());
            builder.setContent(content);

            QixiProto.CrossQixiSendFlowerRespMsg.Builder resp = QixiProto.CrossQixiSendFlowerRespMsg.newBuilder();

            player.getModule(PreReduceModule.class).preReduce(cost);//统一预扣

            CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(targetServerId, GameProtocol.S_QIXI_SEND_FLOWER, player.getUserId(), builder, resp);
            future.thenAccept((SyncResponse syncResponse) -> {
                if (syncResponse.getErrorCode() != 0) {
                    resp.setRet(syncResponse.getErrorCode());
                }
                if (resp.getRet() != -1) {
                    sendFlowerSuccessBack(resp.build());
                } else {
                    QixiProto.QixiSendFlowerRespMsg.Builder waiMsg = QixiProto.QixiSendFlowerRespMsg.newBuilder();
                    waiMsg.setRet(GameErrorCode.E_QIXI_WAIT_SEND_FLOWER_BACK);
                    player.sendPacket(ClientProtocol.U_QIXI_WAIT_SEND_FLOWER_BACK, waiMsg);
                }
            });

            return -1;
        }
    }

    public void sendFlowerSuccessBack(QixiProto.CrossQixiSendFlowerRespMsg resp) {

        waitSendFlowerBackUserIdSet.remove(resp.getTargetUserId());

        Property cost = new Property(resp.getFlowerId(), resp.getFlowerCount());
        player.getModule(PreReduceModule.class).restorePreReduce(cost);//统一返还预扣

        QixiProto.QixiSendFlowerRespMsg.Builder resultMsg = QixiProto.QixiSendFlowerRespMsg.newBuilder();
        resultMsg.setRet(resp.getRet());
        resultMsg.setRemainCanReceive(resp.getRemainCanReceive());
        if (resp.getRet() == 0) {
            long currentTime = DateHelper.getCurrentTime();
            player.getModule(CurrencyModule.class).removeCurrency(cost, eLogMoneyType.QixiActivity, eLogMoneyType.QixiActivitySendFlowerCost);

            GoodsInfo flowerInfo = GoodsMgr.getGoodsById(resp.getFlowerId());
            Property giftReward = QixiMgr.getGiftReward(flowerInfo, resp.getFlowerCount());

            resultMsg.setActivityId(QixiMgr.getConfig().getActivityId());
            resultMsg.setReward(PropertyHelper.parsePropertyToString(giftReward));
            resultMsg.setSendTime(currentTime);
            resultMsg.setFlowerId(resp.getFlowerId());
            resultMsg.setFlowerCount(resp.getFlowerCount());
            resultMsg.setTargetServerId(resp.getUserBaseInfo().getServerId());
            resultMsg.setTargetName(resp.getUserBaseInfo().getNickName());

            player.sendPacket(ClientProtocol.U_QIXI_SEND_FLOWER, resultMsg);

            player.getModule(CurrencyModule.class).addCurrency(giftReward, eLogMoneyType.QixiActivity, eLogMoneyType.QixiActivitySendFlowerReward);

            int addCount = flowerInfo.getParamList().get(0).multiply(BigInteger.valueOf(resp.getFlowerCount())).intValue();
            synchronized (userRelationMap) {
                UserQixiRelationData targetRelation = getTargetRelation(resp.getTargetUserId());
                if (targetRelation == null) {
                    targetRelation = new UserQixiRelationData(QixiMgr.getConfig().getActivityId(), player.getUserId(), resp.getTargetUserId());
                    addTargetRelation(targetRelation);
                }

                targetRelation.setSendFlowerCount(targetRelation.getSendFlowerCount() + addCount);
                targetRelation.setSendTime(currentTime);

                int totalSendCount = 0;
                for (UserQixiRelationData userQixiRelationData : userRelationMap.values()) {
                    totalSendCount += userQixiRelationData.getSendFlowerCount();
                }

                userData.setSendFlowerCount(totalSendCount);
            }
            player.notifyListener(eGamePlayerEventType.QixiSendFlowerAchieve.getValue(), userData.getSendFlowerCount());

            AutoLogMgr.add(new LogQixiSendFlower(QixiMgr.getConfig().getActivityId(), player.getUserId(), resp.getTargetUserId(), resp.getFlowerId(), resp.getFlowerCount(), addCount));

            if (flowerInfo.getParamList().get(4).intValue() == 1) {
                //广播,发到跨服创建数据
                QixiProto.CorssQixiFlowerBroadcastMsg.Builder toCrossMsg = QixiProto.CorssQixiFlowerBroadcastMsg.newBuilder();
                toCrossMsg.setActivityId(QixiMgr.getConfig().getActivityId());
                toCrossMsg.setLeftUserId(player.getUserId());
                toCrossMsg.setRightUserId(resp.getTargetUserId());
                toCrossMsg.setFlowerId(resp.getFlowerId());
                toCrossMsg.setContent(resp.getContent());

                toCrossMsg.setLeftUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
                toCrossMsg.setRightUserInfo(resp.getUserBaseInfo());
                toCrossMsg.setSendTime(currentTime);

                player.sendPacket(CrossProtocol.C_QIXI_SEND_FLOWER_BROADCAST, toCrossMsg);

                long targetServerId = toCrossMsg.getRightUserInfo().getServerId();
                if (!QixiMgr.getConfig().getActivityInfo().getServerIdList().contains(targetServerId)) {
                    //不在同一个活动服,发到另外一个活动服
                    GamePlayerMgr.sendToGameServer(targetServerId, GameProtocol.S_QIXI_GIFT_BROADCAST_FROM_OTHER, player.getUserId(), toCrossMsg, null);
                }
            }
        } else {
            player.sendPacket(ClientProtocol.U_QIXI_SEND_FLOWER, resultMsg);
        }
    }


    /**
     * 收花
     */
    public synchronized QixiProto.CrossQixiSendFlowerRespMsg.Builder receiveFlower(long sendUserId, int flowerId, int flowerCount, String content) {
        //收花的人如果没有活动数据,直接返回0,不往下走。策划又改了,不让收了, 不能往下走。
        QixiProto.CrossQixiSendFlowerRespMsg.Builder resultMsg = QixiProto.CrossQixiSendFlowerRespMsg.newBuilder();
        resultMsg.setRet(0);
        initUserData();
        int ret = checkActivityRet();
        if (ret != 0) {
            return resultMsg.setRet(ret);
        }
        resetOneDay(false);

        GoodsInfo flowerInfo = GoodsMgr.getGoodsById(flowerId);

        if (flowerInfo == null) {
            return resultMsg.setRet(GameErrorCode.E_QIXI_FLOWER_USE_CONFIG_NOT_FOUND);
        }

        int addCount = flowerInfo.getParamList().get(0).multiply(BigInteger.valueOf(flowerCount)).intValue();
        synchronized (userRelationMap) {
            int receiveLimit = flowerInfo.getParamList().get(3).intValue();
            int remainCanReceive = -1;
            resultMsg.setRemainCanReceive(remainCanReceive);
            if (receiveLimit != -1) {
                //有接收数量限制
                int dayCount = 0;
                if (flowerId == QixiMgr.getConfig().getQIXI_PINK_ROSE_ID()) {
                    dayCount = userData.getDayCount1();
                } else if (flowerId == QixiMgr.getConfig().getQIXI_RED_ROSE_ID()) {
                    dayCount = userData.getDayCount2();
                } else if (flowerId == QixiMgr.getConfig().getQIXI_ROMANTIC_ROSE_ID()) {
                    dayCount = userData.getDayCount3();
                }

                if (dayCount >= receiveLimit) {
                    resultMsg.setRemainCanReceive(receiveLimit - dayCount);
                    return resultMsg.setRet(GameErrorCode.E_QIXI_FLOWER_RECEIVE_LIMIT);
                }

                if (dayCount + flowerCount > receiveLimit) {
                    resultMsg.setRemainCanReceive(receiveLimit - dayCount);
                    return resultMsg.setRet(GameErrorCode.E_QIXI_FLOWER_RECEIVE_LIMIT_EX);
                } else {
                    remainCanReceive = receiveLimit - (dayCount + flowerCount);
                    resultMsg.setRemainCanReceive(remainCanReceive);
                }
            }

            if (userGiftList.size() >= QixiMgr.getConfig().getQIXI_GIFT_LIMIT()) {
                return resultMsg.setRet(GameErrorCode.E_QIXI_GIFT_LIMIT);
            }

            UserQixiRelationData targetRelation = getTargetRelation(sendUserId);
            if (targetRelation == null) {
                targetRelation = new UserQixiRelationData(QixiMgr.getConfig().getActivityId(), player.getUserId(), sendUserId);
                addTargetRelation(targetRelation);
            }
            targetRelation.setGetFlowerCount(targetRelation.getGetFlowerCount() + addCount);
            targetRelation.setGetTime(System.currentTimeMillis());

            if (flowerId == QixiMgr.getConfig().getQIXI_PINK_ROSE_ID()) {
                userData.setDayCount1(userData.getDayCount1() + flowerCount);
            } else if (flowerId == QixiMgr.getConfig().getQIXI_RED_ROSE_ID()) {
                userData.setDayCount2(userData.getDayCount2() + flowerCount);
            } else if (flowerId == QixiMgr.getConfig().getQIXI_ROMANTIC_ROSE_ID()) {
                userData.setDayCount3(userData.getDayCount3() + flowerCount);
            }

            int totalValue = 0;

            for (UserQixiRelationData relationData : userRelationMap.values()) {
                totalValue += relationData.getGetFlowerCount();
            }

            userData.setGetFlowerCount(totalValue);
            userData.setLastGetTime(System.currentTimeMillis());
        }

        AutoLogMgr.add(new LogQixiReceiveFlower(QixiMgr.getConfig().getActivityId(), player.getUserId(), sendUserId, flowerId, flowerCount, addCount));

        player.notifyListener(eGamePlayerEventType.QixiUserRank.getValue(), userData.getGetFlowerCount());

        //添加赠礼日志
        UserQixiGiftData userQixiGiftData = new UserQixiGiftData(QixiMgr.getConfig().getActivityId(), player.getUserId(), sendUserId, System.currentTimeMillis());
        userQixiGiftData.setFlowerId(flowerId);
        userQixiGiftData.setFlowerCount(flowerCount);
//        userQixiGiftData.setContent(content);礼物用不到宣言,不存

        addNewGift(userQixiGiftData);

        if(player.getState() == PlayerState.ONLINE) {//玩家在线才执行
            syncUserData();
        }

        return resultMsg;
    }

    public void addNewGift(UserQixiGiftData userQixiGiftData) {
        if (userQixiGiftData == null) {
            return;
        }

        synchronized (userGiftList) {
            userGiftList.add(userQixiGiftData);
        }

    }

    public int searchUser(QixiProto.QixiSearchUserReqMsg reqMsg) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        if (reqMsg.getServerId() == GameServer.getInstance().getServerId()) {
            QixiProto.QixiSearchUserRespMsg.Builder respMsg = QixiMgr.searchUser(reqMsg.getServerId(), reqMsg.getTargetAliasId());
            if (respMsg.getRet() != 0) {
                return respMsg.getRet();
            }
            UserQixiRelationData targetRelation = getTargetRelation(respMsg.getUserRelation().getTargetUserId());
            if (targetRelation != null) {
                QixiProto.QixiRelationTemp.Builder relationTemp = QixiProto.QixiRelationTemp.newBuilder();
                relationTemp.setTargetUserId(targetRelation.getTargetUserId());
                relationTemp.setUserBaseInfo(respMsg.getUserRelation().getUserBaseInfo());
                relationTemp.setSendFlowerCount(targetRelation.getSendFlowerCount());
                relationTemp.setGetFlowerCount(targetRelation.getGetFlowerCount());
                respMsg.setUserRelation(relationTemp);
            }

            player.sendPacket(ClientProtocol.U_QIXI_SEARCH_USER, respMsg);

            return 0;

        } else {

            QixiProto.QixiSearchUserReqMsg.Builder builder = QixiProto.QixiSearchUserReqMsg.newBuilder();
            builder.setActivityId(QixiMgr.getConfig().getActivityId());
            builder.setTargetAliasId(reqMsg.getTargetAliasId());
            builder.setServerId(reqMsg.getServerId());

            QixiProto.QixiSearchUserRespMsg.Builder resp = QixiProto.QixiSearchUserRespMsg.newBuilder();

            CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(reqMsg.getServerId(), GameProtocol.S_QIXI_SEARCH_USER, player.getUserId(), builder, resp);
            future.thenAccept((SyncResponse syncResponse) -> {
                if (syncResponse.getErrorCode() != 0) {
                    resp.setRet(syncResponse.getErrorCode());
                }
                resp.setActivityId(QixiMgr.getConfig().getActivityId());
                UserQixiRelationData targetRelation = getTargetRelation(resp.getUserRelation().getTargetUserId());
                if (targetRelation != null) {
                    QixiProto.QixiRelationTemp.Builder relationTemp = QixiProto.QixiRelationTemp.newBuilder();
                    relationTemp.setTargetUserId(targetRelation.getTargetUserId());
                    relationTemp.setUserBaseInfo(resp.getUserRelation().getUserBaseInfo());
                    relationTemp.setSendFlowerCount(targetRelation.getSendFlowerCount());
                    relationTemp.setGetFlowerCount(targetRelation.getGetFlowerCount());
                    resp.setUserRelation(relationTemp);
                }
                player.sendPacket(ClientProtocol.U_QIXI_SEARCH_USER, resp);
            });

            return -1;
        }
    }

    public int getGiftList() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        Map<Long, Set<Long>> needUserInfoFromOtherServer = new HashMap<>();
        Map<Long, UserQixiGiftData> waitUserInfoGiftMap = new HashMap<>();

        QixiProto.QixiGiftListIdxRespMsg.Builder respMsg = QixiProto.QixiGiftListIdxRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(QixiMgr.getConfig().getActivityId());

        for (UserQixiGiftData userQixiGiftData : userGiftList) {
            long targetUserId = userQixiGiftData.getTargetUserId();

            QixiProto.QixiGiftTemp.Builder builder = QixiProto.QixiGiftTemp.newBuilder();
            builder.setTargetUserId(userQixiGiftData.getTargetUserId());
            builder.setGiftTime(userQixiGiftData.getGiftTime());
            builder.setFlowerId(userQixiGiftData.getFlowerId());
            builder.setFlowerCount(userQixiGiftData.getFlowerCount());
            builder.setContent(userQixiGiftData.getContent());

            PlayerProto.PlayerBaseTempMsg playerBaseTempMsg = QixiMgr.getCacheUserInfo(targetUserId);
            if (playerBaseTempMsg != null) {
                builder.setUserBaseInfo(playerBaseTempMsg);
            } else {
                UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(targetUserId, GameServer.getInstance().getServerId());
                if (userBaseInfo == null) {
                    //本服没有去商会找一下
                    CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(targetUserId);
                    if (unionMember != null) {
                        userBaseInfo = unionMember.getUserBaseInfo();
                    }
                }

                if (userBaseInfo != null) {
                    builder.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                } else {
                    long targetServerId = RelativesMgr.getUserServerId(targetUserId);
                    Set<Long> userIds = needUserInfoFromOtherServer.get(targetServerId);
                    if (userIds == null) {
                        userIds = new HashSet<>();
                        needUserInfoFromOtherServer.put(targetServerId, userIds);
                    }
                    userIds.add(targetUserId);

                    waitUserInfoGiftMap.put(targetUserId, userQixiGiftData);
                }
            }


            respMsg.addGiftIdx(builder);
        }

        player.sendPacket(ClientProtocol.U_QIXI_GIFT_LIST_IDX, respMsg);

        //先发所有礼物的索引,如果有取不到userInfo的,取其他服取回来后,用22295发给客户端做填充.

        for (Map.Entry<Long, Set<Long>> entry : needUserInfoFromOtherServer.entrySet()) {
            Long serverId = entry.getKey();
            Set<Long> userIds = entry.getValue();

            QixiProto.QixiGetUserInfoReqMsg.Builder reqMsg = QixiProto.QixiGetUserInfoReqMsg.newBuilder();
            reqMsg.setActivityId(QixiMgr.getConfig().getActivityId());
            reqMsg.addAllTargetUserId(userIds);
            reqMsg.setReqProtocolType(GameProtocol.S_QIXI_GIFT_LIST);

            QixiProto.QixiGetUserInfoRespMsg.Builder resp = QixiProto.QixiGetUserInfoRespMsg.newBuilder();

            CompletableFuture<SyncResponse> future = GamePlayerMgr.sendToGameServer(serverId, GameProtocol.S_QIXI_GET_USER_INFO, player.getUserId(), reqMsg, resp);
            future.thenAccept((SyncResponse syncResponse) -> {
                if (syncResponse.getErrorCode() != 0) {
                    return;
                }
                if (resp.getReqProtocolType() != GameProtocol.S_QIXI_GIFT_LIST) {
                    return;
                }
                QixiProto.QixiGiftListRespMsg.Builder giftMsg = QixiProto.QixiGiftListRespMsg.newBuilder();
                giftMsg.setActivityId(QixiMgr.getConfig().getActivityId());
                for (QixiProto.QixiRelationTemp temp : resp.getRelationListList()) {
                    long targetUserId = temp.getTargetUserId();
                    QixiMgr.addCacheUserInfo(temp.getTargetUserId(), temp.getUserBaseInfo());
                    UserQixiGiftData userQixiGiftData = waitUserInfoGiftMap.get(targetUserId);
                    if (userQixiGiftData != null) {
                        QixiProto.QixiGiftTemp.Builder giftTemp = QixiProto.QixiGiftTemp.newBuilder();
                        giftTemp.setTargetUserId(userQixiGiftData.getTargetUserId());
                        giftTemp.setGiftTime(userQixiGiftData.getGiftTime());
                        giftTemp.setFlowerId(userQixiGiftData.getFlowerId());
                        giftTemp.setFlowerCount(userQixiGiftData.getFlowerCount());
                        giftTemp.setContent(userQixiGiftData.getContent());
                        giftTemp.setUserBaseInfo(temp.getUserBaseInfo());

                        giftMsg.addGiftList(giftTemp);
                    }
                }

                player.sendPacket(ClientProtocol.U_QIXI_GIFT_LIST, giftMsg);

            });
        }

        return 0;
    }

    public int receiveGift() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        if (userGiftList.isEmpty()) {
            return GameErrorCode.E_QIXI_GIFT_EMPTY;
        }

        Property totalReward = new Property();
        Property showReward = new Property(); //新需求,要求显示收了多少花

        synchronized (userGiftList) {
            for (UserQixiGiftData userQixiGiftData : userGiftList) {
                userQixiGiftData.setStatus(1);
                needUpdateGiftList.add(userQixiGiftData);

                GoodsInfo flowerInfo = GoodsMgr.getGoodsById(userQixiGiftData.getFlowerId());
                if (flowerInfo == null) {
                    continue;
                }

                Property giftReward = QixiMgr.getGiftReward(flowerInfo, userQixiGiftData.getFlowerCount());

                totalReward.addProperty(giftReward);

                showReward.addProperty(new Property(flowerInfo.getGoodsId(), userQixiGiftData.getFlowerCount()));
            }

            userGiftList.clear();
        }

        if (!totalReward.isNothing()) {
            player.getModule(CurrencyModule.class).addCurrency(totalReward, eLogMoneyType.QixiActivity, eLogMoneyType.QixiActivityGiftReward);
        }

        showReward.addProperty(totalReward);

        QixiProto.QixiReceiveGiftRespMsg.Builder respMsg = QixiProto.QixiReceiveGiftRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setActivityId(QixiMgr.getConfig().getActivityId());
        respMsg.setReward(PropertyHelper.parsePropertyToString(showReward));

        player.sendPacket(ClientProtocol.U_QIXI_RECEIVE_GIFT, respMsg);

        syncUserData();

        return 0;
    }

    public long getGiftMostUserId() {
        return QixiMgr.getGiftMostUserIdByRelationMap(userRelationMap);
    }

    public void getBroadcastRewardCrossBack(QixiProto.CrossGetBroadcastRewardRespMsg resultMsg) {
        QixiProto.QixiReceiveBroadcastRewardRespMsg.Builder clientMsg = QixiProto.QixiReceiveBroadcastRewardRespMsg.newBuilder();
        clientMsg.setRet(0);
        if (resultMsg.getRet() != 0) {
            clientMsg.setRet(resultMsg.getRet());
            player.sendPacket(ClientProtocol.U_QIXI_RECEIVE_BROADCAST_REWARD, clientMsg);
            return;
        }

        if (userData.wasGetBroadcast(resultMsg.getBroadcastId())) {
            clientMsg.setRet(GameErrorCode.E_QIXI_BROADCAST_WAS_GET);
            player.sendPacket(ClientProtocol.U_QIXI_RECEIVE_BROADCAST_REWARD, clientMsg);
            return;
        }

        userData.addBroadcastId(resultMsg.getBroadcastId());

        Property broadcastReward = QixiMgr.getConfig().getBroadcastReward();
        player.getModule(CurrencyModule.class).addCurrency(broadcastReward, eLogMoneyType.QixiActivity, eLogMoneyType.QixiActivityBroadcastReward);
        String rewardString = PropertyHelper.parsePropertyToString(broadcastReward);
        clientMsg.setBroadcastId(resultMsg.getBroadcastId());
        clientMsg.setReward(rewardString);

        AutoLogMgr.add(new LogQixiReceiveBroadcast(QixiMgr.getConfig().getActivityId(), player.getUserId(), resultMsg.getBroadcastId(), rewardString));

        player.sendPacket(ClientProtocol.U_QIXI_RECEIVE_BROADCAST_REWARD, clientMsg);

    }

    public int receiveBroadcastReward(long broadcastId) {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return ret;
        }

        if (userData.wasGetBroadcast(broadcastId)) {
            return GameErrorCode.E_QIXI_BROADCAST_WAS_GET;
        }

        if (!userData.wasWatchBroadcast(broadcastId)) {
            return GameErrorCode.E_QIXI_BROADCAST_NOT_WATCH;
        }

        QixiProto.CrossGetBroadcastRewardReqMsg.Builder crossMsg = QixiProto.CrossGetBroadcastRewardReqMsg.newBuilder();
        crossMsg.setActivityId(QixiMgr.getConfig().getActivityId());
        crossMsg.setBroadcastId(broadcastId);

        player.sendPacket(CrossProtocol.C_QIXI_GET_FLOWER_BROADCAST_REWARD, crossMsg);

        return -1;
    }

    public void broadcastCrossBack(QixiProto.CrossQixiBroadcastBackMsg resultMsg) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return;
        }
        removeOverBroadcastId();
        for (QixiProto.QixiFlowerBroadcastMsg broadcastMsg : resultMsg.getBroadcastListList()) {
            if (!userData.getWatchBroadcastList().contains(broadcastMsg.getBroadcastId())) {
                player.sendPacket(ClientProtocol.U_QIXI_FLOWER_BROADCAST, broadcastMsg.toBuilder());
            }
            userData.addWatchBroadcastId(broadcastMsg.getBroadcastId());
        }
    }

    public boolean canChargeSucceed(int mallId) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return false;
        }

        return true;
    }

    public void removeOverBroadcastId() {
        int ret = checkActivityShowRet();
        if (ret != 0) {
            return;
        }
        long currentTime = DateHelper.getCurrentTime();
        if (currentTime - userData.getLastWatchTime() > QixiMgr.getConfig().getQIXI_BROADCASTING_TIME() * DateHelper.MINUTE_MILLIONS + 1 * DateHelper.MINUTE_MILLIONS) {
            //超过有效时间了。所以可以清掉。因为都领不了了。
            userData.getWatchBroadcastList().clear();
            userData.getGetBroadcastList().clear();
            userData.setUpdateOption();
        }
    }

    public Map<Long, UserQixiRelationData> getUserRelationMap() {
        return userRelationMap;
    }

    public int newSearchUser(QixiProto.QixiNewSearchUserReqMsg reqMsg) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        if(reqMsg.getUserIdCount() == 0){
            return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
        }

        QixiProto.QixiNewSearchUserRespMsg.Builder clientMsg = QixiProto.QixiNewSearchUserRespMsg.newBuilder();

        for (Long uid : reqMsg.getUserIdList()) {
            QixiProto.NewQixiRelationTemp.Builder relationTemp = QixiProto.NewQixiRelationTemp.newBuilder();
            UserQixiRelationData targetRelation = getTargetRelation(uid);
            if(targetRelation == null){
                relationTemp.setTargetUserId(uid);
                relationTemp.setSendFlowerCount(0);
                relationTemp.setGetFlowerCount(0);
            }else {
                relationTemp.setTargetUserId(targetRelation.getTargetUserId());
                relationTemp.setSendFlowerCount(targetRelation.getSendFlowerCount());
                relationTemp.setGetFlowerCount(targetRelation.getGetFlowerCount());
            }
            clientMsg.addUserRelation(relationTemp);
        }

        clientMsg.setActivityId(QixiMgr.getConfig().getActivityId());
        clientMsg.setRet(0);
        player.sendPacket(ClientProtocol.U_QIXI_NEW_SEARCH_USER, clientMsg);

        return 0;
    }
}
